home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16935 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  57 lines

  1. Path: gas.physics.usu.edu!pjh
  2. Newsgroups: comp.lang.c++
  3. Subject: operator<< precedence, cout, and weirdness
  4. Message-ID: <1996Apr12.133813.78123@cc.usu.edu>
  5. From: pjh@gas.physics.usu.edu (Paul Hepworth)
  6. Date: 12 Apr 96 13:38:13 MDT
  7. Organization: Utah State University
  8. Nntp-Posting-Host: gas.physics.usu.edu
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. I'm having a hard time figuring out the weird eval order
  12. of these operator<< expressions:
  13.  
  14. Here is the output from the prog below:
  15. 2220
  16. 2220
  17.  
  18. It appears the i++/++i expressions are being evaluated right to
  19. left instead of left to right.
  20. I included a parenthesized version to explicitly specify
  21. the order I think it should already be evaluated in, and it
  22. gives the same result.
  23.  
  24. What's the deal?!
  25.  
  26. #include <stream.h>
  27. int main()
  28. {
  29.   int i=0;
  30.   
  31.   cout << i++ << i << ++i << i++ << endl;
  32.   cout << i << endl;
  33.  
  34.   i=0;
  35.   (((( cout << i++) << i) << ++i) << i++) << endl;
  36.   cout << i << endl;
  37. }
  38.  
  39. I think it should evaluate as follows:
  40. i++, producing integer result 
  41. cout << above result, producing istream&
  42. above result << i, producing istream&
  43. ++i, producing integer
  44. above istream& << above integer result, producing istream&
  45. i++, producing integer
  46. above istream& << above integer, producing istream&
  47. above istream& << endl, producing istream&
  48.  
  49. instead, it seems to evaluate the i++/++i expressions to temporaries,
  50. then cout << tmp1 << tmp2....
  51.  
  52. BTW, with numbers, it evaluates as expected:
  53. 1 << 1 << 2 produces 8, not 16
  54.  
  55.  
  56. Paul
  57.